const { querySql, queryOne, formatJson } = require('../utils/common');
const { body, validationResult, query } = require('express-validator');
const boom = require('boom');
const jwt = require('jsonwebtoken');
const md5 = require('../utils/md5');
const passport = require('passport')
const { tengxun_cos } = require('../config/index')
var fs = require('fs');
var COS = require('cos-nodejs-sdk-v5');
const {
  CODE_ERROR,
  CODE_SUCCESS,
  PRIVATE_KEY,
  JWT_EXPIRED,
  APPID,
  SECRETID,
  SECRETKRY
} = require('../utils/constant');
function register(req, res, next) {
  let { username, password } = req.body
  const query = `insert into admin(username,password) values ('${username}','${password}')`
  console.log(query)
  querySql(query).then(data => {
    res.json(formatJson(data, 'Object'))
  })
}
function login(req, res, next) {
  let { username, password } = req.body;
  const query = `select * from admin where username='${username}' and password='${password}'`;
  querySql(query).then(user => {
    if (!user || user.length === 0) {
      res.json({
        code: CODE_ERROR,
        msg: '用户名或密码错误',
        data: null
      })
    } else {
      // 登录成功，签发一个token并返回给前端
      const token = jwt.sign(
        // payload：签发的 token 里面要包含的一些数据。
        { username },
        // 私钥
        PRIVATE_KEY,
        // 设置过期时间
        { expiresIn: JWT_EXPIRED }
      )
      let token1 = { token: token }
      res.json({
        code: CODE_SUCCESS,
        msg: '登录成功',
        data: Object.assign(user[0], token1)
      })
    }
  })
}
function getAllUser(req, res, next) {
  const query = 'select * from admin'
  querySql(query).then(data => {
    res.json(formatJson(data, 'Array'))
  })
}
function getUserName(req, res, next) {
  let { username } = req.query
  const query = `select * from admin where username='${username}'`
  querySql(query).then(data => {
    res.json(formatJson(data, 'Object'))
  })
}
function adminManage(req, res, next) {
  let { operation } = req.body;
  console.log(req.body);
  //获取想要的操作
  if (operation == 'insert') {
    insertData(req, res)
  } else if (operation == 'delete') {
    deleteData(req, res)
  } else if (operation == 'search') {
    searchData(req, res)
  } else if (operation == 'all') {
    getAllData(req, res)
  } else if (operation == 'update') {
    updateData(req, res)
  }
}
function insertData(req, res) {
  let { form, data } = req.body
  let dataArr = []
  let dataKey = []
  for (let key in data) {
    dataArr.push('"' + data[key] + '"')
    dataKey.push(key)
  }
  console.log(dataArr)
  const query = `insert into ${form} (${dataKey + ''}) values(${dataArr + ''})`
  console.log(query)
  querySql(query).then(result => {
    res.json(formatJson(result, 'Object'))
  })
}
function deleteData(req, res) {
  let { form, data } = req.body
  let key = Object.keys(data)[0]
  const query = `delete from ${form} where ${key}='${data[key]}'`
  querySql(query).then(result => {
    res.json(formatJson(result, 'Object'))
  })
}
function updateData(req, res) {
  let { form, data } = req.body
  //处理数据
  let dataArr = []
  console.log(data)
  let key = Object.keys(data)[0]
  let oldStr = form + "." + key + "=" + '"' + data[key][0] + '"'
  let newStr = key + "=" + '"' + data[key][1] + '"'
  let query = `update ${form} set ${newStr} where ${oldStr};`
  console.log(query)
  querySql(query).then(result => {
    res.json(formatJson(result, 'Object'))
  })
}
function getFormSum(form){
  let query = `SELECT COUNT(*) FROM ${form}`
  return new Promise((resolve)=>{
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
function getFormSumLike(form,like){
  let query = `SELECT COUNT(*) FROM ${form} WHERE ${like}`
  return new Promise((resolve)=>{
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
async function searchData(req, res) {
  let { form, data, size, page } = req.body
  let query = ''
  let min = 0
  console.log(11);
  let sum = await getFormSum(form)
  sum = sum[0]['COUNT(*)']
  console.log(sum)
  //处理分页数据
  if (size != -1) {
    min = size * (page - 1)
  }
  if (Object.keys(data).length > 1) {
    let dataArr = []
    //查询条件不止一个
    for (let key in data) {
      dataArr.push(key + '=' + '"' + data[key] + '"')
    }
    let dataStr = dataArr + ''
    dataStr = dataStr.replace(',', ' and ')
    if (size == -1) {
      query = `select * from ${form} where ${dataStr};`
    } else {
      query = `select * from ${form} where ${dataStr} limit ${min},${size};`
    }
  } else {
    //只有一个查询条件
    let key = Object.keys(data)[0]
    let dataStr = key + '=' + '"' + data[key] + '"'
    if (size == -1) {
      query = `select * from ${form} where ${dataStr};`
    } else {
      query = `select * from ${form} where ${dataStr} limit ${min},${size};`
    }
  }
  console.log(query)
  querySql(query).then(result => {
    let data = {
      list:result,
      sum:sum
    }
    res.json(formatJson(data, 'Normal'))
  })
}
async function getAllData(req, res) {
  let { form, size, page } = req.body
  let sum = await getFormSum(form)
  sum = sum[0]['COUNT(*)']
  //处理分页数据
  if (size != -1) {
    min = size * (page - 1)
  }
  let query
  if (size != -1) {
    query = `select * from ${form} limit ${min},${size};`
  } else {
    query = `select * from ${form}`
  }
  console.log(query)
  querySql(query).then(result => {
    let data = {
      list:result,
      sum:sum
    }
    res.json(formatJson(data, 'Normal'))
  })
}
async function searchLike(req, res) {
  let { form, data, size, page } = req.body
  let min
  if (size != -1) {
    min = size * (page - 1)
  }
  //格式化data
  let key = Object.keys(data)[0]
  let dataStr = key + ' like ' + '"%' + data[key] + '%"'
  let sum = await getFormSumLike(form,dataStr)
  sum = sum[0]['COUNT(*)']
  let query
  if (size == -1) {
    query = `select * from ${form} where ${dataStr};`
  } else {
    query = `select * from ${form} where ${dataStr} limit ${min},${size};`
  }
  console.log(query)
  querySql(query).then(result => {
    let data = {
      list:result,
      sum:sum
    }
    res.json(formatJson(data, 'Normal'))
  })
}
function uploadFile(req, res, next) {
  var cos = new COS({
    AppId: APPID,
    SecretId: SECRETID,
    SecretKey: SECRETKRY,
  });
  console.log(req.file)
  // return 
  // 文件路径
  var filePath = './' + req.file.path;
  // 文件类型
  var temp = req.file.originalname.split('.');
  var fileType = temp[temp.length - 1];
  var lastName = '.' + fileType;
  // 构建图片名
  var fileName = Date.now() + lastName;
  // 图片重命名
  fs.rename(filePath, fileName, (err) => {
    if (err) {
      res.end(JSON.stringify({ status: '102', msg: '文件写入失败' }));
    } else {
      var localFile = './' + fileName;
      var key = fileName;

      // 腾讯云 文件上传
      var params = {
        Bucket: tengxun_cos.Bucket,                         /* 必须 */
        Region: tengxun_cos.Region,                         /* 必须 */
        Key: key,                                           /* 必须 */
        FilePath: localFile,                                /* 必须 */
      }
      cos.sliceUploadFile(params, function (err, data) {
        if (err) {
          fs.unlinkSync(localFile);
          res.end(JSON.stringify({ status: '101', msg: '上传失败', error: JSON.stringify(err) }));
        } else {
          fs.unlinkSync(localFile);
          var imageSrc = 'https://1271981054-1256167451.cos.ap-nanjing.myqcloud.com/' + data.Key;
          console.log(imageSrc)
          res.end(JSON.stringify({ status: '100', msg: '上传成功', imageUrl: imageSrc }));
        }
      });
    }
  })
}
async function getHeadAll(req,res,next) {
   let result = await getHeadData()
   console.log(result[0])
   let imageId = result[0].image_id
   let authorArr = result[0].author_arr!=''?result[0].author_arr.split(','):[]
   let sampleArr = result[0].sample_arr!=''?result[0].sample_arr.split(','):[]
   let showArr = result[0].show_arr!=''?result[0].show_arr.split(','):[]
   let imageInfo = await getImageInfo(imageId) 
   let authorList = await getAuthorList(authorArr)
   let sampleList = await getSampleList(sampleArr)
   let showList = await getShowList(showArr)
   let data = {
     imageInfo:imageInfo,
     authorList:authorList,
     sampleList:sampleList,
     showList:showList,
     date:result[0].date
   }
   res.json(formatJson(data, 'Array'))

}

function getHeadData() {
  return new Promise((resolve) => {
    let query = 'select * from head'
    querySql(query).then(result => {
      resolve(result)
    })
  })
}

function getImageInfo(id){
  return new Promise((resolve)=>{
    let query = `select * from image where id=${id}`
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
function getAuthorList(author_arr){
  let param = ""
  if(author_arr.length==0){
    return []
  }
  author_arr.forEach((item,index) => {
    if(index!=author_arr.length-1){
      param = param + `id=${parseInt(item)} or `
    }else{
      param = param +`id=${parseInt(item)} `
    }
  })
  return new Promise((resolve)=>{
    let query = `select * from author where ${param}`
    console.log(query)
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
function getSampleList(sample_arr){
  let param = ""
  if(sample_arr.length==0){
      return []
  }
  console.log(sample_arr)
  sample_arr.forEach((item,index) => {
    if(index!=sample_arr.length-1){
      param = param + `id=${parseInt(item)} and `
    }else{
      param = param +`id=${parseInt(item)} `
    }
  })
  return new Promise((resolve)=>{
    
    let query = `select * from sample where ${param}`
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
function getShowList(show_arr){
  let param = ""
  if(show_arr.length==0){
    return []
  }
  show_arr.forEach((item,index) => {
    if(index!=show_arr.length-1){
      param = param + `id=${parseInt(item)} and `
    }else{
      param = param +`id=${parseInt(item)} `
    }
  })
  return new Promise((resolve)=>{
    let query = `select * from show where ${param}`
    querySql(query).then(result => {
      resolve(result)
    })
  })
}
async function getAuthorinfo(req,res,next){
  let{author_id} = req.body
  let imageSum = await getAllImage(author_id)
  let sampleSum = await getAllSample(author_id)
  let data = {
    imageSum:imageSum,
    sampleSum:sampleSum
  }
  res.json(formatJson(data, 'Normal'))
}
function getAllImage(author_id){
  return new Promise((resolve)=>{
    const query = `SELECT COUNT(*) FROM image WHERE author_id=${author_id}`
    console.log(query)
    // sum[0]['COUNT(*)']
    querySql(query).then(result => {
      let sum  =result[0]['COUNT(*)']
      resolve(sum)
    })
    
  })
}
function getAllSample(author_id){
  return new Promise((resolve)=>{
    const query = `SELECT COUNT(*) FROM sample WHERE author_id=${author_id}`
    console.log(query)
    // sum[0]['COUNT(*)']
    querySql(query).then(result => {
      let sum  =result[0]['COUNT(*)']
      resolve(sum)
    })
    
  })
}
function deleteArray(req,res,next){
  let {data,form,key} = req.body
  let deleteStr = data.toString()
  const query = `delete from ${form} where ${key} in (${deleteStr})`
  querySql(query).then(result => {
    res.json(formatJson(result, 'Object'))
  })
}
function updateImageInfo(req,res,next){
  let {data,sample_id} = req.body
  const query = `update image set sample_id = ${sample_id} where id in (${data.toString()})`
  querySql(query).then(result => {
    res.json(formatJson(result, 'Object'))
  })
}
module.exports = {
  register,
  login,
  getAllUser,
  getUserName,
  adminManage,
  searchLike,
  uploadFile,
  getHeadAll,
  getAuthorinfo,
  deleteArray,
  updateImageInfo
}
